﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;


namespace SiruEngine.Graphics
{
	public class Camera
	{
		private Vector3 position;
		private float range;
		private float degree_y;
		private float degree_x;
		
		public void Reset()
		{
			position = new Vector3(0, 0, 0);
			range = 5.0f;
			degree_y = 0.0f;
			degree_x = 0.6f;
		}

        public void Range(float r)
        {
            range = r;
        }

		public void RotateX(float dt)
		{
			const float max_90 = (float ) Math.PI / 2.0f;

			degree_x += dt;

			if (degree_x > max_90)
				degree_x = max_90;
			else if (degree_x < 0)
				degree_x = 0;
		}

		public void RotateY(float dy)
		{
			degree_y += dy;
		}

		public void Forward(float d)
		{
			Backward(-d);
		}

		public void Backward(float d)
		{
			range += d;

			if (range < 0.01f)
				range = 0.01f;
		}

		public Matrix View()
		{
			Vector3 cameraPosition = new Vector3(0, range, 0);
			Vector3 up = new Vector3(0, 0, -1);
			Matrix rotationMatrix = Matrix.CreateRotationX(degree_x) * Matrix.CreateRotationY(degree_y);

			cameraPosition = Vector3.TransformNormal(cameraPosition, rotationMatrix);
			cameraPosition = Vector3.Add(cameraPosition, position);

			return Matrix.CreateLookAt(cameraPosition, position, Vector3.TransformNormal(up, rotationMatrix));
		}

        public Vector3 Position
        {
            get
            {
                Vector3 cameraPosition = new Vector3(0, range, 0);
                Matrix rotationMatrix = Matrix.CreateRotationX(degree_x) * Matrix.CreateRotationY(degree_y);

                cameraPosition = Vector3.TransformNormal(cameraPosition, rotationMatrix);
                cameraPosition = Vector3.Add(cameraPosition, position);

                return cameraPosition;
            }
        }
	}
}
